package cn.oversky.eom.rule;

import cn.oversky.eom.utils.ReflectionUtils;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import static cn.oversky.eom.utils.PropertiesUtils.isNotNull;
import static cn.oversky.eom.utils.PropertiesUtils.isNull;
import static cn.oversky.eom.utils.ReflectionUtils.getFieldValue;
import static cn.oversky.eom.utils.ReflectionUtils.Null;


/**
 * @author CorvusY@foxmail.com
 * @date 2018/2/9 10:52.
 * Now is history !
 */
public class FormValid {

    public static Set<ErrorMessage> doRule(Object obj, Map<String, IFormValueRule> rule ) throws IllegalAccessException {
        // 未通过校验的结果集
        Set<ErrorMessage> result = new LinkedHashSet<ErrorMessage>();
        Set<String> fields = rule.keySet();
        for( String field : fields ) {
            Object value = getFieldValue(obj, field);
            IFormValueRule valueRule = rule.get(field);
            // 空值熔断。
            if( isNull( valueRule ) ) {
                continue;
            }
            if( !( value instanceof Null ) ) {
                String errorMessage = valueRule.doRuleReturn(value);
                if( isNotNull( errorMessage ) ) {
                    result.add( new ErrorMessage( errorMessage, field ) );
                }
            }
        }
        return result;
    }

    public static Set<ErrorMessage> doRule( Collection collection, Map<String,IFormValueRule> rule ) throws IllegalAccessException {
        Set<ErrorMessage> result = new LinkedHashSet<ErrorMessage>();
        int i = 0;
        for( Object o : collection ) {
            i ++;
            Set<ErrorMessage> errorMessages = doRule(o, rule);
            for( ErrorMessage errorMessage : errorMessages ) {
                errorMessage.y = i;
            }
            result.addAll( errorMessages );
        }
        return result;
    }

    /**
     * 用于定位校验失败的位置
     */
    public static class ErrorMessage {
        private String message;
        private String field;
        private int y;

        public ErrorMessage(String message, String field) {
            this.message = message;
            this.field = field;
        }

        public String getField() {
            return field;
        }

        public void setField(String field) {
            this.field = field;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }

}
